package com.fenxiangle.yueding.feature.mine.view;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fenxiangle.yueding.R;
import com.fenxiangle.yueding.common.widget.dialog.BounceTopEnter;
import com.fenxiangle.yueding.common.widget.dialog.NormalDialog;
import com.fenxiangle.yueding.common.widget.dialog.OnBtnClickL;
import com.fenxiangle.yueding.common.widget.dialog.SlideBottomExit;
import com.fenxiangle.yueding.entity.bo.OrderBo;
import com.fenxiangle.yueding.entity.bo.PublishDemandBo;
import com.fenxiangle.yueding.entity.bo.TabEntity;
import com.fenxiangle.yueding.entity.bo.UnMsgBo;
import com.fenxiangle.yueding.entity.bo.UnReadCountBo;
import com.fenxiangle.yueding.feature.home.view.UserInfoActivity;
import com.fenxiangle.yueding.feature.mine.view.adapter.PublishOrderAdapter;
import com.fenxiangle.yueding.feature.mine.view.adapter.Share2Activity;
import com.fenxiangle.yueding.feature.order.view.CommentActivity;
import com.fenxiangle.yueding.feature.order.view.ContactDetailActivity;
import com.fenxiangle.yueding.feature.order.view.ReceiveOrderFragment;
import com.fenxiangle.yueding.feature.order.view.ToRatingActivity;
import com.fenxiangle.yueding.feature.publish.contract.PublishContract;
import com.fenxiangle.yueding.feature.publish.dependencies.mine.DaggerPublishComponent;
import com.fenxiangle.yueding.feature.publish.dependencies.mine.PublishPresenterModule;
import com.fenxiangle.yueding.feature.publish.view.PayActivity;
import com.fenxiangle.yueding.feature.publish.view.PublishInviteActivity;
import com.fenxiangle.yueding.framework.api.HomeApi;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.flyco.tablayout.utils.UnreadMsgUtils;
import com.flyco.tablayout.widget.MsgView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.suozhang.framework.component.http.RxDataProcessFactory;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseFragment;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.widget.EmptyView;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static android.content.Context.CLIPBOARD_SERVICE;

public class FragmentPublishOrder extends BaseFragment implements PublishContract.View, OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener, RadioGroup.OnCheckedChangeListener, OnTabSelectListener {
    @BindView(R.id.rv_publish_order)
    RecyclerView mRvPublishDemand;
    @BindView(R.id.btn_radio_publish)
    RadioGroup mBtnRadioPublish;
    Unbinder unbinder;

    Unbinder unbinder1;
    @BindView(R.id.tv_order_show)
    TextView mTvOrderShow;
    Unbinder unbinder2;
    @BindView(R.id.tab_menu)
    CommonTabLayout mTabMenu;

    private PublishOrderAdapter mAdapter;
    @BindView(R.id.smartRefesh)
    SmartRefreshLayout mSmartRefesh;

    private EmptyView mEmptyView;
    private int pageIndex = 1;
    private int pageSize = 10;
    List<PublishDemandBo> mData;

    private Integer mType = null;

    @Inject
    PublishContract.Presenter mPresenter;
    private NormalDialog normalDialog;


    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    private String[] mTitles = {"全部订单", "交易中", "待确认", "待评分", "已完成"};
    private int[] mIconUnselectIds = {
            R.drawable.ic_publish_all, R.drawable.ic_publish_jyz,
            R.drawable.ic_publish_dqr, R.drawable.ic_publish_dpf, R.drawable.ic_publish_ywc};

    private int[] mIconSelectIds = {
            R.drawable.ic_publish_all, R.drawable.ic_publish_jyz,
            R.drawable.ic_publish_dqr, R.drawable.ic_publish_dpf, R.drawable.ic_publish_ywc};
    private CallBackValue callBackValue;


    @Override
    public int attachLayoutRes() {
        return R.layout.fragment_publish_order;
    }

    @Override
    protected void initInjector() {
        DaggerPublishComponent.builder().publishPresenterModule(new PublishPresenterModule(this)).build().inject(this);
    }

    /**
     * fragment与activity产生关联是  回调这个方法
     */
    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        //当前fragment从activity重写了回调接口  得到接口的实例化对象
        callBackValue = (CallBackValue) getActivity();
    }

    @Override
    public void showPublishSuccess(OrderBo s) {

    }

    @Override
    public void showError(String error) {
        showMsg(error);
    }

    @Override
    public void showInsufficientBalance() {

    }

    @Override
    public void showPublishListSuccess(List<PublishDemandBo> workBoPageData) {
        mSmartRefesh.finishRefresh();
        mData = workBoPageData;
        setData(true, mData);
        mAdapter.setEnableLoadMore(true);
    }

    @Override
    public void showPublishListError(String error) {
        if (mSmartRefesh != null) mSmartRefesh.finishRefresh();
        mAdapter.setEmptyView(mEmptyView.getErrorView(error));
        mAdapter.setNewData(null);
        mAdapter.setEnableLoadMore(true);
        mSmartRefesh.finishRefresh();
    }

    @Override
    public void showPublishListMoreSuccess(List<PublishDemandBo> msg) {
        setData(false, msg);
    }

    @Override
    public void showPublishListMoreError(String msg) {
        mAdapter.loadMoreFail();
    }

    @Override
    public void showPublishListEmpty() {
        if (mSmartRefesh != null) mSmartRefesh.finishRefresh();
        mAdapter.setEmptyView(mEmptyView.getEmptyView());
        mAdapter.setNewData(null);
    }

    @Override
    public void showcancleOrderSuccess() {
        showMsg("取消成功！");
        mSmartRefesh.autoRefresh();
    }

    @Override
    public void showConfrimOrderSuccess() {
        showMsg("确认成功！");
        mSmartRefesh.autoRefresh();
    }

    @Override
    public void showConfrimTxSuccess() {
        showMsg("提醒成功！");
    }

    @Override
    public void showWeiQunanOrderSuccess() {
        showMsg("维权成功！");
        mSmartRefesh.autoRefresh();
    }

    public void initAdapter() {
        mSmartRefesh.setEnableLoadMore(false);
        mSmartRefesh.setOnRefreshListener(this);
        mEmptyView = new EmptyView(mRvPublishDemand);
        mRvPublishDemand.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new PublishOrderAdapter();
        mAdapter.bindToRecyclerView(mRvPublishDemand);
        mAdapter.setOnLoadMoreListener(this, mRvPublishDemand);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
    }

    private void initTabMsg() {


        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }

        mTabMenu.setTabData(mTabEntities);
        mTabMenu.setOnTabSelectListener(this);


    }

    @Override
    protected void initView() {
        initTabMsg();
        initAdapter();
        mBtnRadioPublish.check(R.id.btn_order_all);
        normalDialog = new NormalDialog(getActivity());
        normalDialog
                .content("是否维权?")//
                .showAnim(new BounceTopEnter())//
                .dismissAnim(new SlideBottomExit());


    }

    @Override
    public void onStart() {
        super.onStart();
        pageIndex = 1;
        mPresenter.getPublishInviteList(pageIndex, pageSize, mType);
    }

    @Override
    protected void initData() {
        pageIndex = 1;
        mPresenter.getPublishInviteList(pageIndex, pageSize, mType);
        getMsgCount();
        callBackValue.selectCount(true);
    }

    @Override
    protected void initEvent() {
        mBtnRadioPublish.setOnCheckedChangeListener(this);
    }

    private void setData(boolean isRefresh, List data) {
        pageIndex++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < pageSize) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refresh();
    }

    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }


    private void refresh() {
        mAdapter.setEnableLoadMore(false);
        initData();
    }

    private ClipboardManager myClipboard;
    private ClipData myClip;
    RxPermissions rxPermissions;

    private void loadMore() {
        mPresenter.getPublishInviteListMore(pageIndex, pageSize, mType);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        if (view.getId() == R.id.btn_order_ok) {
            switch (mData.get(position).getOrderStatus()) {
                case 0:
                    if (mData.get(position).getType() == 1) {//抢单
                        mPresenter.cancleInvitedOrder(mData.get(position).getOrderId(), "1");
                    } else {
                        mPresenter.cancleInvitedOrder(mData.get(position).getOrderId(), "2");

                    }

                    break;

                case 1://提醒
                    Intent intent = new Intent(getActivity(), PublishInviteActivity.class);
                    intent.putExtra("data", mData.get(position));
                    startActivity(intent);

                    break;
                case 2:
                    if (mData.get(position).getTotalPrice() <= 0) {
                        showMsg("付款金额不能为空");
                        return;
                    }
                    OrderBo payBo = new OrderBo(mData.get(position).getOrderId(), Double.valueOf(mData.get(position).getTotalPrice()));
                    Intent intents = new Intent(getActivity(), PayActivity.class);
                    intents.putExtra("no", payBo);
                    startActivity(intents);
                    break;

                case 3:
                    if (mData.get(position).getType() == 1) {//抢单
                        Intent intent1 = new Intent(getActivity(), ContactDetailActivity.class);
                        intent1.putExtra("orderId", mData.get(position).getOrderId());
                        intent1.putExtra("type", mData.get(position).getType()+"");
                        startActivity(intent1);
                    } else {
                        mPresenter.cancleInvitedOrder(mData.get(position).getOrderId(), "2");
                    }
                    break;
                case 4://抢单确定
                    mPresenter.cancleConfrimOrder(mData.get(position).getOrderId(), mData.get(position).getUserUid());
                    break;
                case 5:
                    if (mData.get(position).getType() == 1) {
                        Intent intentS = new Intent(getActivity(), CommentActivity.class);
                        intentS.putExtra("rating", mData.get(position));
                        intentS.putExtra("orderId", mData.get(position).getOrderId());
                        intentS.putExtra("user_id", mData.get(position).getUserUid());
                        startActivity(intentS);
                    } else {
                        Intent intentS = new Intent(getActivity(), ToRatingActivity.class);
                        intentS.putExtra("rating", mData.get(position));
                        startActivity(intentS);
                    }

                    break;
                case 6:
                    Intent intentaa = new Intent(getActivity(), Share2Activity.class);
                    startActivity(intentaa);
                    break;
                default:
                    break;
            }
        } else if (view.getId() == R.id.btn_call_phone) {

            rxPermissions = new RxPermissions(getActivity());
            rxPermissions
                    .request(Manifest.permission.CALL_PHONE)
                    .subscribe(granted -> {
                        if (granted) { // Always true pre-M
                            diallPhone(mData.get(position).getUserPhone());
                        } else {
                            showMsg("请先开启拨打电话权限!");
                        }
                    });

        } else if (view.getId() == R.id.btn_copy_wx) {
            if (TextUtils.isEmpty(mData.get(position).getWeChat())) {
                T.showShort("该用户未设置微信号！");
            } else {
                myClipboard = (ClipboardManager) getActivity().getSystemService(CLIPBOARD_SERVICE);
                myClip = ClipData.newPlainText("text", mData.get(position).getWeChat());
                myClipboard.setPrimaryClip(myClip);
                T.showShort("文本已复制！");
            }

        } else if (view.getId() == R.id.btn_publis_toweiquan) {
            if (mData.get(position).getOrderStatus() == 3) {
                Intent intent = new Intent(getActivity(), ContactDetailActivity.class);
                intent.putExtra("type", "1");
                intent.putExtra("orderId", mData.get(position).getOrderId());
                intent.putExtra("user_id", mData.get(position).getUserUid());
                startActivity(intent);
            } else {
                normalDialog.setOnBtnClickL(
                        new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                try {
                                    if (normalDialog != null) {
                                        normalDialog.superDismiss();
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        },
                        new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                mPresenter.txWeiquan(mData.get(position).getOrderId(), mData.get(position).getUserUid());
                                normalDialog.dismiss();
                            }
                        });

                normalDialog.show();
            }


        } else if (view.getId() == R.id.btn_publis_querendingdan) {
            if (mData.get(position).getOrderStatus() == 3) {//取消交易
                NormalDialog normalDialog = new NormalDialog(getActivity());
                normalDialog.title("")
                        .content("确定取消?")//
                        .btnNum(2)
                        .showAnim(new BounceTopEnter())//
                        .dismissAnim(new SlideBottomExit());
                normalDialog.setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        if (normalDialog.isShowing()) {
                            normalDialog.superDismiss();
                        }
                    }
                }, new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        if (mData.get(position).getType() == 1) {//抢单
                            mPresenter.cancleInvitedOrder(mData.get(position).getOrderId(), "1");
                        } else {
                            mPresenter.cancleConfrimOrder(mData.get(position).getOrderId(), mData.get(position).getUserUid());
                        }
                        normalDialog.superDismiss();
                    }
                });
                normalDialog.show();

            } else {//确定订单
                mPresenter.cancleConfrimOrder(mData.get(position).getOrderId(), mData.get(position).getUserUid());
            }
        } else if (view.getId() == R.id.iv_my_publish_head || view.getId() == R.id.tv_my_publish_username) {
            Intent intent = new Intent(getActivity(), UserInfoActivity.class);
            intent.putExtra("id", mData.get(position).getUserUid());
            startActivity(intent);
        } else if (view.getId() == R.id.btn_my_publish_activist) { //异常处理
            Intent intent = new Intent(getActivity(), ContactDetailActivity.class);
            intent.putExtra("orderId", mData.get(position).getOrderId());
            startActivity(intent);
        }

    }

    public void diallPhone(String phoneNum) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_CALL);
        //url:统一资源定位符
        //uri:统一资源标示符（更广）
        intent.setData(Uri.parse("tel:" + phoneNum));
        //开启系统拨号器
        startActivity(intent);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.btn_order_all:
                mType = null;
                mTvOrderShow.setText("全部订单");
                break;
            case R.id.btn_order_trading:
                mType = 3;
                mTvOrderShow.setText("交易中");
                break;
            case R.id.btn_order_unconfrimed:
                mType = 4;
                mTvOrderShow.setText("待确认");
                break;
            case R.id.btn_order_completed:
                mTvOrderShow.setText("待评分");
                mType = 5;
                break;
            case R.id.btn_order_unscore:
                mType = 1;
                break;
        }
        initData();
    }


    @Override
    public void onTabSelect(int position) {
        switch (position) {
            case 0:
                mType = null;
                mTvOrderShow.setText("全部订单");
                break;
            case 1:
                mType = 3;
                mTvOrderShow.setText("交易中");

                break;
            case 2:
                mType = 4;
                mTvOrderShow.setText("待确认");
                break;
            case 3:
                mTvOrderShow.setText("待评分");
                mType = 5;
                break;
            case 4:
                mType = 1;
                break;
        }
        initData();

    }

    @Override
    public void onTabReselect(int position) {

    }


    private void getMsgCount() {
        AM.api().createApiService(HomeApi.class)
                .selectDiffMessageCount(new UnMsgBo(4 + ""))
                .compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer())
                .subscribe(new Observer<UnReadCountBo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(UnReadCountBo msgBos) {
                        if (msgBos != null) {
                            if (msgBos.getMyPublishTrading() > 0) {

                                //两位数
                                mTabMenu.showMsg(1, msgBos.getMyPublishTrading());
                                mTabMenu.setMsgMargin(1, -10, 5);

                                MsgView rtv_2_3 = mTabMenu.getMsgView(1);
                                if (rtv_2_3 != null) {
                                    rtv_2_3.setStrokeColor(getResources().getColor(R.color.yuffff4b28));
                                    rtv_2_3.setBackgroundColor(getResources().getColor(R.color.yuffff4b28));
                                    rtv_2_3.setTextColor(getResources().getColor(R.color.bg_060000));
                                    rtv_2_3.setTextSize(10);
                                    DisplayMetrics dm = rtv_2_3.getResources().getDisplayMetrics();
                                    int size = (int) (14 * dm.density);
                                    UnreadMsgUtils.setSize(rtv_2_3, size);
                                }
                            }
                            if (msgBos.getMyPublishWaitingConfirm() > 0) {
                                //三位数
                                mTabMenu.showMsg(2, msgBos.getMyPublishWaitingConfirm());
                                mTabMenu.setMsgMargin(2, -10, 5);

                                MsgView rtv_2_4 = mTabMenu.getMsgView(2);
                                if (rtv_2_4 != null) {
                                    rtv_2_4.setStrokeColor(getResources().getColor(R.color.yuffff4b28));
                                    rtv_2_4.setBackgroundColor(getResources().getColor(R.color.yuffff4b28));
                                    rtv_2_4.setTextColor(getResources().getColor(R.color.bg_060000));
                                    rtv_2_4.setTextSize(10);
                                    DisplayMetrics dm = rtv_2_4.getResources().getDisplayMetrics();
                                    int size = (int) (14 * dm.density);
                                    UnreadMsgUtils.setSize(rtv_2_4, size);
                                }
                            }
                            if (msgBos.getMyPublishWaitingConfirm() > 0) {

                                //三位数
                                mTabMenu.showMsg(3, msgBos.getMyPublishWaitingConfirm());
                                mTabMenu.setMsgMargin(3, -10, 5);

                                MsgView rtv_2_5 = mTabMenu.getMsgView(3);
                                if (rtv_2_5 != null) {
                                    rtv_2_5.setStrokeColor(getResources().getColor(R.color.yuffff4b28));
                                    rtv_2_5.setBackgroundColor(getResources().getColor(R.color.yuffff4b28));
                                    rtv_2_5.setTextColor(getResources().getColor(R.color.bg_060000));
                                    rtv_2_5.setTextSize(10);
                                    DisplayMetrics dm = rtv_2_5.getResources().getDisplayMetrics();
                                    int size = (int) (14 * dm.density);
                                    UnreadMsgUtils.setSize(rtv_2_5, size);
                                }
                            }

                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    //定义一个回调接口
    public interface CallBackValue {
        public void selectCount(boolean isSelect);
    }

}
